<?php

namespace app\admin\controller;

use think\Cookie;
use think\Cache;

class Everyone extends \app\common\controller\Base {

    /**
     * @title 退出
     */
    public function logout() {
        
        $token = cookie('token_admin' . APP_SALT);

        Cache::rm($token);

        Cookie::delete('token_admin' . APP_SALT);

        $this->success('退出成功', url('admin/everyone/login'));
    }

    /**
     * @title 登录
     * @return type
     */
    public function login() {


        if (request()->isPost()) {

            //  后端验证
            $post = request()->post();
            foreach ($post as $key => $value) {
                $post[$key] = trim($value);
            }


            $username = $post['username'] ?? '';
            $password = $post['password'] ?? '';

            // echo my_md5($password); exit;

            $system_user = db('system_user')
                    ->where('username', $username)
                    ->where('password', my_md5($password))
                    ->field('id,username,nickname')
                    ->find();

            if ($system_user) {
                // 生成一个随机token
                $token = uniqid();

                // 保存到浏览器端
                cookie('token_admin' . APP_SALT, $token);

                // 保存到服务器端,保存登录一周
                cache($token, json_encode($system_user), 3600 * 24 * 7);
                
                //
                $this->success('', url('admin/index/index'));
            } else {
                $this->error('登录失败');
            }
        } else {

            return view();
        }
    }

}
